package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

/**
 * 处理文件上传下载
 */
@RestController
@RequestMapping("common")
public class CommonController {
    //注入yml文件中保存路径位置
    @Value("${reggie.path}")
    private String BASE_PATH;
    /**
     * 文件上传
     *
     */
    @PostMapping("upload")
    public R<String> upload(MultipartFile file){
         //获取文件名
        String filename = file.getOriginalFilename();
        //根据文件名切割出后缀名
        String substring = filename.substring(filename.lastIndexOf("."));
        //生成随机UUID 防止文件名重复覆盖
        String UUIDFileName = UUID.randomUUID().toString()+substring;
        //判断文件夹是否存在
        File file1 = new File(BASE_PATH);
        if (!file1.exists()) {
            //不存在 创建
            file1.mkdirs();
        }
        try {
            //设置保存路径
            file.transferTo(new File(BASE_PATH+UUIDFileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //把保存的文件名返回给前端 前端要根据文件下载
        return R.success(UUIDFileName);
    }
    /**
     * 文件下载
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response){
        try {
            //创建文件输入流
            FileInputStream fileInputStream = new FileInputStream(new File(BASE_PATH + name));
            //创建文件输出流对象
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
